package com.hanlp.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hanlp.bean.*;

import java.util.ArrayList;
import java.util.List;

/**
 * JSON解析工具类
 * 用于将东方财富API返回的JSON数据解析为Bean对象
 */
public class JsonUtil {
    
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 解析股票实时行情数据
     * @param jsonResponse JSON响应字符串
     * @return StockRealTimeData对象
     */
    public static StockRealTimeData parseStockRealTimeData(String jsonResponse) {
        try {
            JsonNode rootNode = objectMapper.readTree(jsonResponse);
            JsonNode dataNode = rootNode.path("data");
            
            if (dataNode.isNull() || !dataNode.isArray() || dataNode.size() == 0) {
                return null;
            }
            
            JsonNode stockNode = dataNode.get(0);
            return parseStockDataFromNode(stockNode);
            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 解析股票列表数据
     * @param jsonResponse JSON响应字符串
     * @return ApiResponse<List<StockRealTimeData>>对象
     */
    public static ApiResponse<List<StockRealTimeData>> parseStockList(String jsonResponse) {
        try {
            JsonNode rootNode = objectMapper.readTree(jsonResponse);
            JsonNode dataNode = rootNode.path("data");
            JsonNode diffNode = dataNode.path("diff");
            
            if (diffNode.isNull() || !diffNode.isArray()) {
                return ApiResponse.error("数据格式错误");
            }
            
            List<StockRealTimeData> stockList = new ArrayList<>();
            for (JsonNode stockNode : diffNode) {
                StockRealTimeData stock = parseStockDataFromNode(stockNode);
                if (stock != null) {
                    stockList.add(stock);
                }
            }
            
            int total = dataNode.path("total").asInt(0);
            return ApiResponse.success(stockList, "获取股票列表成功");
            
        } catch (Exception e) {
            return ApiResponse.error("解析股票列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 解析可转债实时行情数据
     * @param jsonResponse JSON响应字符串
     * @return ConvertibleBondData对象
     */
    public static ConvertibleBondData parseConvertibleBondRealTimeData(String jsonResponse) {
        try {
            JsonNode rootNode = objectMapper.readTree(jsonResponse);
            JsonNode dataNode = rootNode.path("data");
            
            if (dataNode.isNull() || !dataNode.isArray() || dataNode.size() == 0) {
                return null;
            }
            
            JsonNode bondNode = dataNode.get(0);
            return parseBondDataFromNode(bondNode);
            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 解析可转债列表数据
     * @param jsonResponse JSON响应字符串
     * @return ApiResponse<List<ConvertibleBondData>>对象
     */
    public static ApiResponse<List<ConvertibleBondData>> parseConvertibleBondList(String jsonResponse) {
        try {
            JsonNode rootNode = objectMapper.readTree(jsonResponse);
            JsonNode dataNode = rootNode.path("data");
            JsonNode diffNode = dataNode.path("diff");
            
            if (diffNode.isNull() || !diffNode.isArray()) {
                return ApiResponse.error("数据格式错误");
            }
            
            List<ConvertibleBondData> bondList = new ArrayList<>();
            for (JsonNode bondNode : diffNode) {
                ConvertibleBondData bond = parseBondDataFromNode(bondNode);
                if (bond != null) {
                    bondList.add(bond);
                }
            }
            
            int total = dataNode.path("total").asInt(0);
            return ApiResponse.success(bondList, "获取可转债列表成功");
            
        } catch (Exception e) {
            return ApiResponse.error("解析可转债列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 解析指数数据
     * @param jsonResponse JSON响应字符串
     * @return ApiResponse<List<IndexData>>对象
     */
    public static ApiResponse<List<IndexData>> parseIndexData(String jsonResponse) {
        try {
            JsonNode rootNode = objectMapper.readTree(jsonResponse);
            JsonNode dataNode = rootNode.path("data");
            JsonNode diffNode = dataNode.path("diff");
            
            if (diffNode.isNull() || !diffNode.isArray()) {
                return ApiResponse.error("数据格式错误");
            }
            
            List<IndexData> indexList = new ArrayList<>();
            for (JsonNode indexNode : diffNode) {
                IndexData index = parseIndexDataFromNode(indexNode);
                if (index != null) {
                    indexList.add(index);
                }
            }
            
            return ApiResponse.success(indexList, "获取指数数据成功");
            
        } catch (Exception e) {
            return ApiResponse.error("解析指数数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 解析板块数据
     * @param jsonResponse JSON响应字符串
     * @return ApiResponse<List<BlockData>>对象
     */
    public static ApiResponse<List<BlockData>> parseBlockData(String jsonResponse) {
        try {
            JsonNode rootNode = objectMapper.readTree(jsonResponse);
            JsonNode dataNode = rootNode.path("data");
            JsonNode diffNode = dataNode.path("diff");
            
            if (diffNode.isNull() || !diffNode.isArray()) {
                return ApiResponse.error("数据格式错误");
            }
            
            List<BlockData> blockList = new ArrayList<>();
            for (JsonNode blockNode : diffNode) {
                BlockData block = parseBlockDataFromNode(blockNode);
                if (block != null) {
                    blockList.add(block);
                }
            }
            
            int total = dataNode.path("total").asInt(0);
            return ApiResponse.success(blockList, "获取板块数据成功");
            
        } catch (Exception e) {
            return ApiResponse.error("解析板块数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 解析K线数据
     * @param jsonResponse JSON响应字符串
     * @return KLineData对象
     */
    public static KLineData parseKLineData(String jsonResponse) {
        try {
            JsonNode rootNode = objectMapper.readTree(jsonResponse);
            JsonNode dataNode = rootNode.path("data");
            
            if (dataNode.isNull()) {
                return null;
            }
            
            KLineData klineData = new KLineData();
            klineData.setName(dataNode.path("name").asText());
            klineData.setCode(dataNode.path("code").asText());
            klineData.setMarket(dataNode.path("market").asInt());
            klineData.setDecimal(dataNode.path("decimal").asInt());
            klineData.setDktotal(dataNode.path("dktotal").asInt());
            
            JsonNode klinesNode = dataNode.path("klines");
            if (klinesNode.isArray()) {
                List<KLineData.KLineItem> klineItems = new ArrayList<>();
                for (JsonNode klineNode : klinesNode) {
                    String klineStr = klineNode.asText();
                    KLineData.KLineItem item = parseKLineItem(klineStr);
                    if (item != null) {
                        klineItems.add(item);
                    }
                }
                klineData.setKlines(klineItems);
            }
            
            return klineData;
            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    // 私有辅助方法
    
    /**
     * 从JsonNode解析股票数据
     */
    private static StockRealTimeData parseStockDataFromNode(JsonNode node) {
        try {
            StockRealTimeData stock = new StockRealTimeData();
            stock.setF1(node.path("f1").asInt());
            stock.setF2(node.path("f2").asDouble());
            stock.setF3(node.path("f3").asDouble());
            stock.setF4(node.path("f4").asDouble());
            stock.setF5(node.path("f5").asLong());
            stock.setF6(node.path("f6").asDouble());
            stock.setF7(node.path("f7").asDouble());
            stock.setF8(node.path("f8").asDouble());
            stock.setF9(node.path("f9").asDouble());
            stock.setF10(node.path("f10").asDouble());
            stock.setF11(node.path("f11").asDouble());
            stock.setF12(node.path("f12").asText());
            stock.setF13(node.path("f13").asInt());
            stock.setF14(node.path("f14").asText());
            stock.setF15(node.path("f15").asDouble());
            stock.setF16(node.path("f16").asDouble());
            stock.setF17(node.path("f17").asDouble());
            stock.setF18(node.path("f18").asDouble());
            stock.setF20(node.path("f20").asLong());
            stock.setF21(node.path("f21").asLong());
            stock.setF22(node.path("f22").asDouble());
            stock.setF23(node.path("f23").asText());
            stock.setF24(node.path("f24").asDouble());
            stock.setF25(node.path("f25").asDouble());
            stock.setF62(node.path("f62").asDouble());
            stock.setF115(node.path("f115").asText());
            stock.setF128(node.path("f128").asText());
            stock.setF140(node.path("f140").asText());
            stock.setF141(node.path("f141").asInt());
            stock.setF136(node.path("f136").asDouble());
            stock.setF152(node.path("f152").asInt());
            return stock;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 从JsonNode解析可转债数据
     */
    private static ConvertibleBondData parseBondDataFromNode(JsonNode node) {
        try {
            ConvertibleBondData bond = new ConvertibleBondData();
            // 设置基本字段
            bond.setSecurityCode(node.path("f12").asText());
            bond.setSecurityNameAbbr(node.path("f14").asText());
            
            // 设置实时行情字段
            bond.setF43(node.path("f43").asDouble());
            bond.setF44(node.path("f44").asDouble());
            bond.setF45(node.path("f45").asDouble());
            bond.setF46(node.path("f46").asDouble());
            bond.setF60(node.path("f60").asDouble());
            bond.setF47(node.path("f47").asDouble());
            bond.setF48(node.path("f48").asDouble());
            bond.setF169(node.path("f169").asDouble());
            bond.setF170(node.path("f170").asDouble());
            bond.setF57(node.path("f57").asDouble());
            bond.setF58(node.path("f58").asDouble());
            bond.setF161(node.path("f161").asDouble());
            bond.setF162(node.path("f162").asDouble());
            bond.setF163(node.path("f163").asDouble());
            
            return bond;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 从JsonNode解析指数数据
     */
    private static IndexData parseIndexDataFromNode(JsonNode node) {
        try {
            IndexData index = new IndexData();
            index.setF1(node.path("f1").asInt());
            index.setF2(node.path("f2").asDouble());
            index.setF3(node.path("f3").asDouble());
            index.setF4(node.path("f4").asDouble());
            index.setF5(node.path("f5").asLong());
            index.setF6(node.path("f6").asDouble());
            index.setF7(node.path("f7").asDouble());
            index.setF8(node.path("f8").asDouble());
            index.setF9(node.path("f9").asDouble());
            index.setF10(node.path("f10").asDouble());
            index.setF11(node.path("f11").asDouble());
            index.setF12(node.path("f12").asText());
            index.setF13(node.path("f13").asInt());
            index.setF14(node.path("f14").asText());
            index.setF15(node.path("f15").asDouble());
            index.setF16(node.path("f16").asDouble());
            index.setF17(node.path("f17").asDouble());
            index.setF18(node.path("f18").asDouble());
            index.setF20(node.path("f20").asLong());
            index.setF21(node.path("f21").asLong());
            index.setF22(node.path("f22").asDouble());
            index.setF23(node.path("f23").asText());
            index.setF24(node.path("f24").asDouble());
            index.setF25(node.path("f25").asDouble());
            index.setF62(node.path("f62").asDouble());
            index.setF115(node.path("f115").asText());
            index.setF128(node.path("f128").asText());
            index.setF140(node.path("f140").asText());
            index.setF141(node.path("f141").asInt());
            index.setF136(node.path("f136").asDouble());
            index.setF152(node.path("f152").asInt());
            return index;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 从JsonNode解析板块数据
     */
    private static BlockData parseBlockDataFromNode(JsonNode node) {
        try {
            BlockData block = new BlockData();
            block.setF1(node.path("f1").asInt());
            block.setF2(node.path("f2").asDouble());
            block.setF3(node.path("f3").asDouble());
            block.setF4(node.path("f4").asDouble());
            block.setF5(node.path("f5").asLong());
            block.setF6(node.path("f6").asDouble());
            block.setF7(node.path("f7").asDouble());
            block.setF8(node.path("f8").asDouble());
            block.setF9(node.path("f9").asDouble());
            block.setF10(node.path("f10").asDouble());
            block.setF11(node.path("f11").asDouble());
            block.setF12(node.path("f12").asText());
            block.setF13(node.path("f13").asInt());
            block.setF14(node.path("f14").asText());
            block.setF15(node.path("f15").asDouble());
            block.setF16(node.path("f16").asDouble());
            block.setF17(node.path("f17").asDouble());
            block.setF18(node.path("f18").asDouble());
            block.setF20(node.path("f20").asLong());
            block.setF21(node.path("f21").asLong());
            block.setF22(node.path("f22").asDouble());
            block.setF23(node.path("f23").asText());
            block.setF24(node.path("f24").asDouble());
            block.setF25(node.path("f25").asDouble());
            block.setF62(node.path("f62").asDouble());
            block.setF115(node.path("f115").asText());
            block.setF128(node.path("f128").asText());
            block.setF140(node.path("f140").asText());
            block.setF141(node.path("f141").asInt());
            block.setF136(node.path("f136").asDouble());
            block.setF152(node.path("f152").asInt());
            return block;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 解析K线项数据
     */
    private static KLineData.KLineItem parseKLineItem(String klineStr) {
        try {
            String[] parts = klineStr.split(",");
            if (parts.length < 11) {
                return null;
            }
            
            KLineData.KLineItem item = new KLineData.KLineItem();
            item.setDate(parts[0]);
            item.setOpen(Double.parseDouble(parts[1]));
            item.setClose(Double.parseDouble(parts[2]));
            item.setHigh(Double.parseDouble(parts[3]));
            item.setLow(Double.parseDouble(parts[4]));
            item.setVolume(Long.parseLong(parts[5]));
            item.setTurnover(Double.parseDouble(parts[6]));
            item.setAmplitude(Double.parseDouble(parts[7]));
            item.setChangePercent(Double.parseDouble(parts[8]));
            item.setChangeAmount(Double.parseDouble(parts[9]));
            item.setTurnoverRate(Double.parseDouble(parts[10]));
            
            return item;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}